package com.huixh.train.business.controller.web;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.ObjUtil;
import com.huixh.train.common.resp.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author huixh
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Value("${spring.profiles.active}")
    private String active;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private HttpServletResponse response;

    private static final String CAPTCHA_KEY = "captcha:";

    private static final String DEV_VALUE = "dev";

    @GetMapping("/createCaptcha/{uuid}")
    public void captcha(@PathVariable("uuid") String uuid) {
        try {
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40);
            String code = lineCaptcha.getCode();
            System.out.println(code);
            redisTemplate.opsForValue().set(CAPTCHA_KEY+uuid,code);
            redisTemplate.expire(CAPTCHA_KEY+uuid,5, TimeUnit.MINUTES);
            // 设置响应的内容类型为PNG图像
            response.setContentType("image/png");
            // 防止图像被浏览器缓存
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            // 记录错误日志或者根据实际情况处理异常
            logger.error("生成图像验证码时出错：", e);
            // 可能还需要设置响应状态码为500（内部服务器错误）
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/checkCaptcha/{uuid}")
    public Result<String> checkCaptcha(@PathVariable("uuid")String uuid,String code){
        if (DEV_VALUE.equals(active)){
            return Result.success();
        } else {
            String captchaKey = CAPTCHA_KEY + uuid;
            logger.info("查询验证码 key：【{}】",captchaKey);
            Object cacheCode = redisTemplate.opsForValue().get(captchaKey);
            if (ObjUtil.isEmpty(cacheCode)) {
                return Result.fail("验证码已失效");
            } else {
                assert cacheCode != null;
                String lowerCase = ((String) cacheCode).toLowerCase();

                if (lowerCase.equals(code.toLowerCase())) {
                    redisTemplate.delete(CAPTCHA_KEY + uuid);
                    return Result.success("验证码验证成功！");
                } else {
                    return Result.fail("验证码错误");
                }
            }
        }
    }
}
